package com.dgut.usermodule.shiroDao;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.dgut.usermodule.dao.UserJpaRepository;
import com.dgut.usermodule.entity.Permission;
import com.dgut.usermodule.entity.User;


public class ShiroReal extends AuthorizingRealm{

	@Autowired
	private UserJpaRepository dao;
	/**
	 * 用户验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) arg0;
		String userName = upToken.getUsername();
		User user = dao.findByUserName(userName);
		SimpleAuthenticationInfo info = null;
		if (user!=null) {
			Object principals = userName;
			Object credentials = user.getPassword();
			String realName = this.getName();
			info = new SimpleAuthenticationInfo(principals, credentials,realName);
		}else {
			throw new AuthenticationException();
		}
		 
		return info;
	}
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		
		String userName = arg0.toString();
		User user = dao.findByUserName(userName);
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		if (user!=null) {
			List<Permission> pers = user.getPerms();
			List<String> perssions = new ArrayList<String>();
				for(Permission p:pers) {
					perssions.add(p.getIdentifier());
				}
			simpleAuthorizationInfo.addStringPermissions(perssions);
		}else {
			throw new AuthenticationException();
		}
		return simpleAuthorizationInfo;
	}
}
